//授权类操作
//首先在微信小程序设置部分添加授权,类似如下设置
// "permission": {
// 	  "scope.userLocation": {
// 		"desc": "小程序将使用定位功能"
// 	  }
// }

import { instance } from '@/common/ajax.js' // 全局挂载引入，配置相关在该index.js文件里修改

/**
 * @param {Object} config 设置配置,
 * scope是权限名称,success获取成功后的操作,fail获取失败后的操作
 * title是提示框的标题,content是提示框的内容
 */
function getAuthorizeInfo(config){
	if(typeof(config.need_setting)!='boolean'){
		config.need_setting=true
	}
	
	uni.authorize({
		scope: config.scope,
		success() { // 允许授权
			config.success()
		},
		fail(){    // 拒绝授权
			if(config.need_setting){
				openConfirm(config);
			}else{
				config.fail()
			}
		}
	})
}

/**
 * 取得具体设置权限
 */
function openConfirm(config){
	uni.showModal({
		title: config.title,
		content: config.content,
		success: (res)=> {
			if (res.confirm) {
				uni.openSetting({
				   success(res) {
					  if(res.authSetting[config.scope]){
						  config.success()
					  }else{
						  config.fail()
					  }
				   }
				});// 打开地图权限设置
			} else if (res.cancel) {
				config.fail()
			}
		},
		fail() {
			config.fail()
		}
	});
}

//取得在缓存中是否有权限成功的信息
function hasAuth(config){
	
	return new Promise((resolve, reject) => {
		uni.getSetting({
			success(res) {
				if(res.authSetting[config.scope]===true){
					resolve()
				}else{
					reject()
				}
			},
			fail() {
				reject()
			}
		})
	})
	
}


//获取Gps定位授权
function getGpsAuth(config){
	config.title=config.title||'请求授权当前位置'
	config.content=config.content||'如果您拒绝了授权,将无法获得周边信息。'
	config.scope='scope.userLocation'
	
	getAuthorizeInfo(config)
}

//获取Gps定位授权
function getWritePhotosAlbumAuth(config){
	config.title=config.title||'请求授权保存图片到相册'
	config.content=config.content||'如果您拒绝了授权,您可以截图保存图片。'
	config.scope='scope.writePhotosAlbum'
	
	getAuthorizeInfo(config)
}

//是否有GPS权限
function hasGpsAuth(){
	let config={}
	config.scope='scope.userLocation'
	
	hasAuth(config).then(()=>{
		return true;
	}).catch(()=>{
		return false;
	})
}

//检测是否设置GPS信息
function checkAndGetGpsAuth(config){
	let hasAuth=hasGpsAuth()
	if(hasAuth){
		config.success()
	}else{
		getGpsAuth(config)
	}
}

//检测是否具有用户权限
function checkHasUserAuth(config){
	let user_detail=uni.getStorageSync("user_detail")
	if(typeof(user_detail)!='object'){
		//无权限
		config.fail(1)
	}else if(user_detail.isAuth==false){
		//未获得微信认证
		config.fail(2)
	}else{
		if(config.success){
			config.success()
		}
	}
}

//获取gps信息,immediately立即更新位置
function getUserLocation() {
	return new Promise((resolve, reject) => {
		let gps=uni.getStorageSync("gps")
		let now=new Date().getTime()
		if(gps.expire&&gps.expire>now){
			resolve(gps)
		}else{
			uni.getLocation({
			    type: 'gcj02',
			    success: function (location) {
					
					getUserLocationDetail(location).then((address_detail)=>{
						
						let gps=makeGpsObj(address_detail)
						
						instance.post('/user/setLatLng',gps).then((userAreaInfo)=>{
								
								gps.expire=now+60*60*1000
								uni.setStorageSync("gps",gps)
								
								resolve(gps)
							})
					}).catch((err)=>{
						reject(err)
					})
					
			    },
				fail:(err)=>{
					console.log(err)
					reject(err)
				}
			});
		}
	})				
}

function getUserLocationNoUpdate() {
	return new Promise((resolve, reject) => {
		let gps=uni.getStorageSync("gps")
		let now=new Date().getTime()
		if(gps.expire&&gps.expire>now){
			resolve(gps)
		}else{
			uni.getLocation({
			    type: 'gcj02',
			    success: function (location) {
					
					getUserLocationDetail(location).then((address_detail)=>{
						
						let gps=makeGpsObj(address_detail)
						
						uni.setStorageSync("gps",gps)
						
						resolve(gps)
						
					}).catch((err)=>{
						reject(err)
					})
					
			    },
				fail:(err)=>{
					console.log(err)
					reject(err)
				}
			});
		}
	})				
}

function makeGpsObj(address_detail){
	let areaId=address_detail.ad_info.adcode	
	let address=address_detail.address_component	
	let gpsObj={
		lat:address_detail.location.lat,
		lng:address_detail.location.lng,
		area:address.district,
		areaId:areaId,
		city:address.city,
		cityId:areaId.substr(0,4).concat("00"),
		province:address.province,
		provinceId:areaId.substr(0,2).concat("0000"),
		street:address.street,
	}
	return gpsObj;
}

//获取gps详细信息
function getUserLocationDetail(gps) {
	return new Promise((resolve, reject) => {
		let gps_detail=uni.getStorageSync("gps_detail")
		let util = require('./util.js');
		if(gps_detail&&util.getDistance(gps.longitude,gps.latitude,gps_detail.location.lng,gps_detail.location.lat)<10){
			console.log("location:from local")
			resolve(gps_detail)
		}else{
			var QQMapWX = require('./qqmap-wx-jssdk/qqmap-wx-jssdk.min.js');
			var qqmapsdk = new QQMapWX({
				    key: 'FZ2BZ-PWO32-DTBUJ-CDQZN-2RQL7-ZGF54'
			});
			qqmapsdk.reverseGeocoder({
				location:gps.latitude+','+gps.longitude,
				success: function (res) {
					uni.setStorageSync("gps_detail",res.result)
					resolve(res.result)
				},
				fail:(err)=>{
					reject(err)
				}
			})
		}
	})				
}

//获取即时gps详细信息
function getUserLocationNow(gps) {
	return new Promise((resolve, reject) => {
			var QQMapWX = require('./qqmap-wx-jssdk/qqmap-wx-jssdk.min.js');
			var qqmapsdk = new QQMapWX({
				    key: 'FZ2BZ-PWO32-DTBUJ-CDQZN-2RQL7-ZGF54'
			});
			qqmapsdk.reverseGeocoder({
				location:gps.latitude+','+gps.longitude,
				success: function (res) {
					resolve(res.result)
				},
				fail:(err)=>{
					reject(err)
				}
			})
	})				
}

//获取点所在方向
function getLocationDirection(mylat,mylng,tlat,tlng){	
	let latd=tlat-mylat
	let lngd=tlng-mylng
	if(latd==0&&lngd==0){
		return "当前位置"
	}
	
	if(latd>0&&lngd==0){
		return "北方"
	}	
	if(latd>0&&lngd>0){
		return "东北方"
	}
	if(latd>0&&lngd<0){
		return "西北方"
	}
	
	if(latd<0&&lngd==0){
		return "南方"
	}
	if(latd<0&&lngd>0){
		return "东南方"
	}
	if(latd<0&&lngd<0){
		return "西南方"
	}
	
	if(latd==0&&lngd>0){
		return "东方"
	}
	
	if(latd==0&&lngd<0){
		return "西方"
	}
	
	return "未知"
	
}

//导出
module.exports = {
	getGpsAuth,
	hasGpsAuth,
	checkAndGetGpsAuth,
	getWritePhotosAlbumAuth,
	getUserLocation,
	getUserLocationNoUpdate,
	getLocationDirection,
	getUserLocationDetail,
	getUserLocationNow,
	checkHasUserAuth
}